#!/usr/bin/env python
# -*- coding:utf-8 -*-
import threading
import Queue

class threadPool:
    def __init__(self,thread_num=2,): #设置线程池开始的数量
        self.requestQueue=Queue.Queue() #实例化两个队列，请求队列和结果队列
        self.resultQueue=Queue.Queue()
        self.threads=[]
        self.createworkers(thread_num)

    def createworkers(self,thread_num):
        for i in range(thread_num):
            thread=workerThread(self.requestQueue,self.resultQueue) #实例化每个线程，启动
            self.threads.append(thread)
        print self.threads
        #[<workerThread(Thread-1, started 11656)>, <workerThread(Thread-2, started 10540)>,......]

    def putRequest(self,callable,arg=None):
        self.requestQueue.put((callable,arg))
        #把执行方法和参数(<function myhandle at 0x0000000002695EB8>, (0,), {})放到请求队列

    def wait(self): #调用join等待它执行完
        for thread in self.threads:
            thread.join()

class workerThread(threading.Thread):
    def __init__(self,requestQueue,resultQueue,**kwargs):
        threading.Thread.__init__(self,**kwargs)
        self.requestQueue=requestQueue
        self.resultQueue=resultQueue
        self.start()    #启动了线程，（Thread-1, started 9540），run起来监听

    def run(self):
        while True:
            try:
                '''
                print self.requestQueue.get()
                (<function myhandle at 0x0000000002695EB8>, None)
                '''
                callable,arg=self.requestQueue.get()    #从请求列表中获取一个job
                result=callable(arg)    #开始处理这个job
                print result   #打印每次请求的返回时间
                self.resultQueue.put("%s:%s"%(self.getName(),result))   #处理完的结果放入结果队列
            except Queue.Empty:
                break
            except:
                print sys.exc_info()

###usage example###
if __name__ == '__main__':
    import urllib
    import time
    import sys

    def myhandle(url):
        '''
        请求某网站n次，从结果队列得到它的返回时间
        '''
        try:
            time.sleep(1)
            start_time=time.time()
            urllib.urlopen("http://www.baidu.com")
            end_time=time.time()
            response_time=(end_time-start_time)*1000  #计算连接网站的时间，毫秒
            return  response_time
        except:
            print  sys.exc_info()

    pool=threadPool(5)  #创建线程池，池中m个线程
    for i in range(30): #请求n次
        pool.putRequest(myhandle)
    time.sleep(10)
    print pool.resultQueue.qsize()
    pool.wait()     #等待执行完毕
    print '线程池中的线程正在等待连接......'

